package com.csmht.tododemo.until;

import com.csmht.tododemo.constant.MessageConstant;
import com.csmht.tododemo.exiception.BaseException;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class VisitorUrlUntil {

    // 私有密钥变量 - 16字节(128位)，符合AES密钥长度要求
    private static final byte[] SECRET_KEY = {
            0x21, 0x43, 0x65, (byte) 0x87, 0x09, (byte) 0xab, (byte) 0xcd, (byte) 0xef,
            (byte) 0xfe, (byte) 0xdc, (byte) 0xba, (byte) 0x90, 0x78, 0x56, 0x34, 0x12
    };

    // 加密算法常量
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    // 密钥对象
    private static final SecretKey secretKey;

    // 静态初始化块，初始化密钥
    static {
        secretKey = new SecretKeySpec(SECRET_KEY, ALGORITHM);
    }

    /**
     * 加密字符串（使用URL安全的Base64）
     * @param plainText 待加密的明文
     * @return 加密后的URL安全Base64字符串
     */
    public static String encrypt(String plainText) {
        if (plainText == null || plainText.isEmpty()) {
            return plainText;
        }

        byte[] encryptedBytes = null;
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new BaseException(MessageConstant.SER_DIE);
        }

        // 使用URL安全的Base64编码器（无填充符）
        return Base64.getUrlEncoder().withoutPadding().encodeToString(encryptedBytes);
    }

    /**
     * 解密字符串（使用URL安全的Base64）
     * @param encryptedText 加密后的URL安全Base64字符串
     * @return 解密后的明文
     */
    public static String decrypt(String encryptedText) {
        if (encryptedText == null || encryptedText.isEmpty()) {
            return encryptedText;
        }

        try {
            // 使用URL安全的Base64解码器
            byte[] encryptedBytes = Base64.getUrlDecoder().decode(encryptedText);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new BaseException(MessageConstant.TODO_NULL);
        }
    }
}
